import React, { Component } from "react";
import { Table, Pagination } from "antd";
import { object, func, array } from "prop-types";

/**
 * getTableListApi 获取表格数据API
 * queryParams 表格查询参数 params
 */
class TableComponent extends Component {
  _isMounted = false; // 这个变量是用来标志当前组件是否挂载
  state = {
    list: [], // 数据源
    loading: false, // 加载loading控制
    total: 0,
    listQuery: {
      pageNum: 1,
      pageSize: 10,
    },
  };

  componentDidUpdate(prevProps) {
    const propsQueryParams = this.props.queryParams;
    if (
      JSON.stringify(propsQueryParams) !== JSON.stringify(prevProps.queryParams)
    ) {
      this.setState(
        (state) => ({
          listQuery: {
            ...state.listQuery,
            ...propsQueryParams,
          },
        }),
        () => {
          this.fetchData();
        }
      );
    }
  }

  componentDidMount() {
    this._isMounted = true;
    this.fetchData();
  }
  componentWillUnmount() {
    this._isMounted = false;
  }

  fetchData = () => {
    this.setState({ loading: true });
    this.props.getTableListApi(this.state.listQuery).then((response) => {
      this.setState({ loading: false });
      // 这个地方需要根据后端返回的结构去定
      const { list, total } = response.data;
      if (this._isMounted) {
        this.setState({ list: list || response.data, total });
      }
      this.props.onGetData && this.props.onGetData(response.data)
    });
  };

  changePage = (pageNum, pageSize) => {
    this.setState(
      (state) => ({
        listQuery: {
          ...state.listQuery,
          pageNum,
        },
      }),
      () => {
        this.fetchData();
      }
    );
  };
  changePageSize = (current, pageSize) => {
    this.setState(
      (state) => ({
        listQuery: {
          ...state.listQuery,
          pageNum: 1,
          pageSize,
        },
      }),
      () => {
        this.fetchData();
      }
    );
  };
  render() {
    return (
      <>
        <Table
          bordered
          rowKey={(record) => record[this.props.idName || 'id']}
          columns={this.props.columns}
          dataSource={this.state.list}
          loading={this.state.loading}
          pagination={false}
          {...(this.props.tableConfig || {})}
        ></Table>
        <br />
        <Pagination
          total={this.state.total}
          pageSizeOptions={["10", "20", "40"]}
          showTotal={(total) => `Total ${total}`}
          onChange={this.changePage}
          current={this.state.listQuery.pageNum}
          onShowSizeChange={this.changePageSize}
          showSizeChanger
          // showQuickJumper
          hideOnSinglePage={true}
        />
      </>
    );
  }
}

TableComponent.propTypes = {
  getTableListApi: func,
  queryParams: object,
  columns: array,
};

export default TableComponent;
